<template>
  <a-drawer
    :width="640"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    unmountOnClose
  >
    <template #title> {{ conditionConfig.pointName }}</template>
    <a-form auto-label-width :model="flowConditionGroup">
      <a-form-item
        class="item"
        field="tempName"
        label="配置优先级"
        validate-trigger="input"
        required
      >
        <a-space direction="vertical" size="large">
          <a-select
            placeholder="请选择"
            v-model="conditionConfig.priority"
            style="width: 300px"
          >
            <a-option
              v-for="index in conditionsConfig.conditionNodes.length - 1"
              :key="index"
              :value="index"
              >优先级{{ index }}</a-option
            >
          </a-select>
        </a-space>
      </a-form-item>
      <a-space direction="vertical" fill>
        <template
          v-for="(group, groupIndex) in flowConditionGroup"
          :key="group.id"
        >
          <a-card
            hoverable
            :title="group.groupName"
            :header-style="{ background: '#eee' }"
          >
            <template #extra>
              <a-link @click="delConditionGroup(group, groupIndex)">
                <icon-delete style="color: red" />
              </a-link>
            </template>
            <a-form-item
              v-for="(item, index) in group.conditionItemsList"
              :key="index"
              :label="getCtlName(item)"
            >
              <div style="width: 100%">
                <!-- 发起人 -->
                <template v-if="!item.ctlId">
                  <div class="condition">
                    <div
                      style="
                        border: 1px solid #c9cdd4;
                        width: 100%;
                        border-radius: 4px;
                        display: flex;
                        flex-wrap: wrap;
                        min-height: 30px;
                        cursor: text;
                      "
                      @click="
                        tagClick(item.compareValueThree, groupIndex, index)
                      "
                    >
                      <a-tag
                        v-for="tag in (item.compareValueThree as any)"
                        :key="tag.id"
                        closable
                        style="margin: 5px"
                        @close="closeTag(tag.id)"
                        >{{ tag.name }}</a-tag
                      >
                    </div>

                    <a-link
                      style="width: 30px"
                      @click="delCondition(group, item, index)"
                    >
                      <icon-delete style="color: red" />
                    </a-link>
                  </div>
                </template>
                <!-- 非发起人  -->
                <template v-else>
                  <div class="condition">
                    <a-space
                      :direction="
                        Number(item.comparatorType) === 5
                          ? 'vertical'
                          : 'horizontal'
                      "
                    >
                      <a-select
                        placeholder="请选择"
                        v-model="item.comparatorType"
                        @change="comparatorChange(item)"
                      >
                        <a-option
                          v-for="comparator in comparatorList"
                          :key="comparator.key"
                          :value="comparator.key"
                        >
                          {{ comparator.lable }}
                        </a-option>
                      </a-select>
                      <!-- 介于两数之间 -->
                      <template v-if="Number(item.comparatorType) === 5">
                        <div>
                          <a-space>
                            <a-input v-model="item.compareValueOne" />
                            <a-select
                              placeholder="请选择"
                              v-model="item.comparatorOne"
                              @change="comparatorChange(item)"
                            >
                              <a-option :value="1" v-text="'<'"> </a-option>
                              <a-option :value="2" v-text="'≤'"> </a-option>
                            </a-select>
                            <div :style="{ whiteSpace: 'nowrap' }">
                              {{ getCtlName(item) }}
                            </div>
                            <a-select
                              placeholder="请选择"
                              v-model="item.comparatorTwo"
                              @change="comparatorChange(item)"
                            >
                              <a-option :value="1" v-text="'<'"> </a-option>
                              <a-option :value="2" v-text="'≤'"> </a-option>
                            </a-select>
                            <a-input v-model="item.compareValueTwo" />
                          </a-space>
                        </div>
                      </template>
                      <!-- 单个比较符和比较值 -->
                      <template v-else>
                        <a-input v-model="item.compareValueOne" />
                      </template>
                    </a-space>
                    <a-link
                      style="width: 30px"
                      @click="delCondition(group, item)"
                    >
                      <icon-delete style="color: red" />
                    </a-link>
                  </div>
                </template>
              </div>
            </a-form-item>
            <a-button type="primary" @click="addCondition(group)">
              添加条件
            </a-button>
          </a-card>
          <a-modal
            v-model:visible="modalVisible"
            @ok="personOk"
            @cancel="personCancel"
          >
            <template #title> 选择条件 </template>
            <a-checkbox-group v-model:model-value="conditionValue">
              <a-checkbox value="fqr"> 发起人 </a-checkbox>
              <template v-if="ctlList.length">
                <a-checkbox
                  v-for="item in ctlList"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.cnName }}
                </a-checkbox>
              </template>
            </a-checkbox-group>
          </a-modal>
          <span v-if="groupIndex < flowConditionGroup.length - 1">或</span>
        </template>

        <a-button type="primary" @click="addConditionGroup()">
          添加条件组
        </a-button>
      </a-space>
    </a-form>
  </a-drawer>
  <HumanMadal
    v-model:visible="humanModalVisible"
    v-model:data="currenHuman"
    @submit="humanSet"
  />
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import { useFlowStore } from '@/store/index';
import * as flowApi from '@/apis/flowPanelPoint/index';
import type {
  ConditionGroup,
  ConditionItemsList
} from '@/apis/flowPanelPoint/type';
import { getFlowCtlList } from '@/apis/flowFormCtl';
import { useRoute } from 'vue-router';
import HumanMadal from './HumanMadal/index.vue';
import { cloneDeep } from 'lodash';
import { FlowForm } from '@/apis/flowFormCtl/type';

const humanModalVisible = ref(false);
const currenHuman = ref<any[]>([]);
const currentIndex = ref<number[]>([0, 0]);
const tagClick = (item: any, groupIndex: number, index: number) => {
  currentIndex.value = [groupIndex, index];
  currenHuman.value = item ? cloneDeep(item) : [];
  humanModalVisible.value = true;
};
const closeTag = (id: number) => {
  console.log(id);
};
const humanSet = () => {
  const group = flowConditionGroup.value[currentIndex.value[0]];
  const condition = group.conditionItemsList || [];
  currenHuman.value.forEach((human) => {
    human.objId = human.id;
  });
  condition[currentIndex.value[1]].compareValueThree = currenHuman.value;
};
const route = useRoute();
const props = withDefaults(
  //参数说明
  defineProps<{
    conditionForm: any;
    conditionId?: number;
  }>(),
  {}
);
const personModalVisible = ref(false);
const modalVisible = ref(false);
const currentGroup = ref<ConditionGroup>();
const conditionValue = ref<any[]>([]);
//添加条件
const addCondition = (group: ConditionGroup) => {
  currentGroup.value = group;
  conditionValue.value = [];
  // 查找条件选项
  group.conditionItemsList?.forEach((condition: ConditionItemsList) => {
    if (!condition.ctlId) {
      conditionValue.value.push('fqr');
    } else {
      conditionValue.value.push(condition.ctlId);
    }
  });

  modalVisible.value = true;
};
const store = useFlowStore();
const closeDrawer = () => {
  store.setCondition(false);
};
let visible = computed({
  get() {
    return store.conditionDrawer;
  },
  set() {
    closeDrawer();
  }
});
const handleCancel = () => {
  store.setCondition(false);
};
let conditionConfig = ref<any>();
let conditionsConfig = ref({
  conditionNodes: []
});
let PriorityLevel = ref('');
watch(
  () => store.conditionsConfig1,
  (val: any) => {
    conditionsConfig.value = val.value;
    PriorityLevel.value = val.priority;
    conditionConfig.value = val.priority
      ? conditionsConfig.value.conditionNodes[val.priority - 1]
      : { nodeUserList: [], conditionList: [] };
  }
);
const flowConditionGroup = ref<ConditionGroup[]>([]);
watchEffect(async () => {
  if (conditionConfig.value?.id) {
    let pointId = conditionConfig.value.id;
    const res = await flowApi.getFlowConditionGroupList({ pointId });
    flowConditionGroup.value = res?.list || [];
    flowConditionGroup.value.forEach((item) => {
      item.conditionItemsList?.forEach((ele) => {
        ele.compareValueThree =
          typeof ele.compareValueThree === 'string'
            ? JSON.parse(ele.compareValueThree)
            : [];
      });
    });
  }
});
//条件用到的控件列表
const ctlList = ref<FlowForm[]>([]);
const getCtlList = async () => {
  ctlList.value = [];
  const ownerId = Number(route.query.id);

  let res = await getFlowCtlList(ownerId);
  if (!res || !res.formInfo) return;
  const { controlDetailList, subsetDetailList } = res.formInfo;
  ctlList.value = [...(controlDetailList || [])];
  subsetDetailList?.forEach((item) => {
    const { controlDetailList: controlDetailList2 } = item;
    if (!controlDetailList2?.length) return;
    ctlList.value = [...(ctlList.value || []), ...(controlDetailList2 || [])];
  });
  ctlList.value = ctlList.value.filter((item) => item.isUseCondition === 1);
  // ctlList.value = [...(controlDetailList || []), ...(subsetDetailList || [])];
  // ctlList.value.sort((a: any, b: any) => a.orderNo - b.orderNo);
};
const getCtlName = (data: ConditionItemsList) => {
  if (!data.ctlId) return '发起人';
  const ctlItem = ctlList.value.find((item: any) => item.id === data.ctlId);
  return ctlItem?.cnName || '错误';
};
watch(
  () => visible.value,
  (val: boolean) => {
    if (val) {
      getCtlList();
      init();
    }
  }
);
/**
 * 添加条件组
 */
const addConditionGroup = (ctlId = 0) => {
  let condition: ConditionGroup = {
    groupName: '条件组',
    pointId: conditionConfig.value.id,
    conditionItemsList: [
      {
        ctlId,
        comparatorType: 1,
        comparatorOne: 1,
        comparatorTwo: 1,
        compareValueOne: '',
        compareValueTwo: '',
        compareValueThree: '',
        conditionItemType: ctlId === 0 ? 1 : 2
      }
    ]
  };
  flowConditionGroup.value.push(condition);
};
const personCancel = () => {
  personModalVisible.value = false;
};
let emits = defineEmits(['change']);
const personOk = () => {
  if (!conditionValue.value.includes('fqr')) {
    const index = currentGroup.value?.conditionItemsList?.findIndex(
      (item) => item.conditionItemType === 1
    );
    if (
      currentGroup.value?.conditionItemsList?.length === 1 &&
      !conditionValue.value.length
    ) {
      const groupIndex = flowConditionGroup.value.findIndex(
        (group) => group.id === currentGroup.value?.id
      );
      flowConditionGroup.value.splice(groupIndex, 1);
      return;
    }
    if (typeof index === 'number' && index >= 0) {
      currentGroup.value?.conditionItemsList?.splice(index, 1);
    }
  }
  ctlList.value.forEach((ctl) => {
    if (
      conditionValue.value.includes(ctl.id) ||
      !currentGroup.value?.conditionItemsList?.length
    )
      return;

    const index = currentGroup.value.conditionItemsList.findIndex(
      (item) => item.ctlId === ctl.id
    );
    if (index < 0) return;
    if (
      currentGroup.value.conditionItemsList.length === 1 &&
      !conditionValue.value.length
    ) {
      const groupIndex = flowConditionGroup.value.findIndex(
        (group) => group.id === currentGroup.value?.id
      );
      flowConditionGroup.value.splice(groupIndex, 1);
      return;
    }
    currentGroup.value.conditionItemsList.splice(index, 1);
  });
  // 遍历选中的控件
  conditionValue.value.forEach((cValue: any) => {
    if (cValue === 'fqr') {
      const index = currentGroup.value?.conditionItemsList?.findIndex(
        (item) => item.conditionItemType === 1
      );
      if (typeof index === 'number' && index < 0) {
        // 没有找到则添加条件
        const conditionItem: ConditionItemsList = {
          ctlId: 0,
          comparatorType: 1,

          conditionItemType: 1,
          compareValueOne: '',
          compareValueTwo: ''
        };
        currentGroup.value?.conditionItemsList?.push(conditionItem);
      }
    } else {
      const index = currentGroup.value?.conditionItemsList?.findIndex(
        (item) => item.ctlId === cValue
      );
      if (typeof index === 'number' && index < 0) {
        const ctlItem = ctlList.value.find((ctl) => ctl.id === cValue);
        // 没有找到则添加条件
        const conditionItem: ConditionItemsList = {
          ctlId: cValue,
          ctlName: ctlItem?.cnName,
          comparatorType: 1,
          comparatorOne: 1,
          comparatorTwo: 1,
          conditionItemType: 2,
          compareValueOne: '',
          compareValueTwo: ''
        };
        currentGroup.value?.conditionItemsList?.push(conditionItem);
      }
    }
  });
  personModalVisible.value = false;
};
const delConditionItemIds = ref<number[]>([]);
const delConditionGroupIds = ref<number[]>([]);
const addConditionGroupData = ref<ConditionGroup[]>([]);
const editConditionGroupData = ref<ConditionGroup[]>([]);
const editConditionGroupData2 = ref<ConditionGroup[]>([]);
const init = () => {
  delConditionItemIds.value = [];
  delConditionGroupIds.value = [];
  addConditionGroupData.value = [];
  editConditionGroupData.value = [];
  editConditionGroupData2.value = [];
};
const handleOk = async () => {
  const copyData = cloneDeep(flowConditionGroup.value);
  // 添加的条件组
  //1组id为空，则是添加，
  //组id存在，则需判断条件项id是否存在，在则是编辑，反之是添加
  copyData.forEach((item) => {
    let addItemData: ConditionItemsList[] = [];
    let editItemData: ConditionItemsList[] = [];
    item.conditionItemsList?.forEach((ele) => {
      ele.compareValueThree = JSON.stringify(ele.compareValueThree);
      ele.groupsId = item.id;
      if (!ele.id) {
        addItemData.push(ele);
      } else {
        editItemData.push(ele);
      }
    });

    if (!item.id) {
      addConditionGroupData.value.push(item);
    } else {
      if (addItemData.length) {
        editConditionGroupData.value.push({
          ...item,
          conditionItemsList: addItemData
        });
      }
      if (editItemData.length) {
        editConditionGroupData2.value.push({
          ...item,
          conditionItemsList: editItemData
        });
      }
    }
  });

  // 先删除条件项
  if (delConditionItemIds.value.length) {
    await flowApi.delFlowConditionItemByIds({ ids: delConditionItemIds.value });
  }
  // 删除条件组
  if (delConditionGroupIds.value.length) {
    await flowApi.delFlowConditionGroupByIds({
      ids: delConditionGroupIds.value
    });
  }
  if (editConditionGroupData.value.length) {
    await flowApi.editFlowConditionGroup(editConditionGroupData.value);
  }
  if (editConditionGroupData2.value.length) {
    await flowApi.editFlowConditionGroup(editConditionGroupData2.value);
  }
  if (addConditionGroupData.value.length) {
    await flowApi.AddFlowConditionGroup(addConditionGroupData.value);
  }
  console.log('copyData', copyData);

  // closeDrawer();
  // emits("change");
};
const comparatorList = [
  { key: 1, lable: '大于' },
  { key: 2, lable: '小于' },
  { key: 3, lable: '大于等于' },
  { key: 4, lable: '小于等于' },
  { key: 5, lable: '介于两数之间' },
  { key: 6, lable: '不包含' },
  { key: 7, lable: '包含' }
];
const comparatorChange = (conditionItem: ConditionItemsList) => {
  // conditionItem.comparatorOne = 0;
  // conditionItem.comparatorTwo = 0;
  // conditionItem.compareValueOne = "";
  // conditionItem.compareValueTwo = "";
};
//删除条件组
const delConditionGroup = (
  conditionGroup: ConditionGroup,
  conditionGroupIndex: number
) => {
  if (!conditionGroup.id) {
    flowConditionGroup.value.splice(conditionGroupIndex, 1);
    return;
  }
  const groupIndex = flowConditionGroup.value.findIndex(
    (group) => group.id === conditionGroup.id
  );
  if (groupIndex < 0) return;
  const groupItem = flowConditionGroup.value[groupIndex];
  if (!groupItem.id) return;
  groupItem.conditionItemsList?.forEach((item) => {
    if (!item.id) return;
    delConditionItemIds.value.push(item.id);
  });
  flowConditionGroup.value.splice(groupIndex, 1);
  delConditionGroupIds.value.push(groupItem.id);
};
//删除条件项
const delCondition = (
  conditionGroup: ConditionGroup,
  conditionItem: ConditionItemsList,
  conditionItemIndex: number
) => {
  if (!conditionGroup.conditionItemsList?.length) return;
  if (!conditionItem.id) {
    conditionGroup.conditionItemsList.splice(conditionItemIndex, 1);
    return;
  }
  const index = conditionGroup.conditionItemsList.findIndex(
    (item) => item.id === conditionItem.id
  );
  if (index < 0) return;
  const conditionItems = conditionGroup.conditionItemsList[index];

  conditionGroup.conditionItemsList?.splice(index, 1);
  if (!conditionItems.id) return;
  delConditionItemIds.value.push(conditionItems.id);
};
</script>

<style lang="less" scoped>
.condition {
  display: flex;
}
</style>
